import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import { Icon } from '../icon';
import { Spinner } from '../spinner';

export interface IToastProps {
  onClick?: React.MouseEventHandler;
  children?: React.ReactNode;
  icon?: string;
  color?: string;
  loading?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

// 封装通用toast函数
const toastFactory = (iconType: string, iconColor: string) => (text: string, duration?: number) => {
  const ele = document.createElement('div');
  document.body.appendChild(ele);
  ReactDOM.render(<Toast icon={iconType} color={iconColor}>{text}</Toast>, ele);
  const hide = () => {
    ReactDOM.unmountComponentAtNode(ele);
    document.body.removeChild(ele);
  };
  if ( duration ) {
  setTimeout(() => {
    hide();
    }, duration);
  }
  return { hide };
};

// 带loading特性的toast函数
const Loading = () => (text: string, duration?: number) => {
  const ele = document.createElement('div');
  document.body.appendChild(ele);
  ReactDOM.render(<Toast loading>{text}</Toast>, ele);
  const hide = () => {
    ReactDOM.unmountComponentAtNode(ele);
    document.body.removeChild(ele);
  };
  if ( duration ) {
  setTimeout(() => {
    hide();
    }, duration);
  }
  return { hide };
};

export class Toast extends React.Component<IToastProps, {}> {
  public static propTypes = {
    children: PropTypes.node,
    icon: PropTypes.string,
    color: PropTypes.string,
    className: PropTypes.string,
    style: PropTypes.object,
  };

  // 导出函数
  public static success = toastFactory('check-circle', '#43b52c');
  public static warn = toastFactory('warn-triangle', '#ffa126');
  public static error = toastFactory('close-solid', '#e22e33');
  public static loading = Loading();

  constructor(props: IToastProps) {
    super(props);
  }
  public render() {
    return (
      <div className={classNames('br-toast', this.props.className)} style={this.props.style}>
        <div className="br-toast__body" >
          {this.props.icon ? <Icon className="br-toast__icon"
            type={this.props.icon} color={this.props.color}> </Icon>
            : null}
          {this.props.loading ? <Spinner className="br-toast__gifIcon"/>
            : null}
          <div className="br-toast__content" >{this.props.children}</div>
        </div>
      </div>
    );
  }
}
